package com.hk.huakangcompany.controller;

import com.hk.huakangcompany.commons.security.CommonResult;
import com.hk.huakangcompany.model.WxRole;
import com.hk.huakangcompany.model.WxRolePermissionRelation;
import com.hk.huakangcompany.model.vo.Result;
import com.hk.huakangcompany.service.WxRolePermissionRelationService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: aerfazhe
 * @Date: 2021/7/26 10:43
 * @Statement: 角色权限 前端控制器
 */
@RestController
@RequestMapping("/role-permission")
public class WxRolePermissionRelationController {

    @Autowired
    private WxRolePermissionRelationService rolePermissionRelationService;

    @ApiOperation("通过角色Id查询所属权限ID集合")
    @GetMapping("/findByRoleId/{id}")
    public Result findByRoleId(@PathVariable Integer id) {
        List<WxRolePermissionRelation> rolePermissionRelationList = rolePermissionRelationService.findByRoleId(id);
        List<Integer> permissionIds = rolePermissionRelationList.stream().map(WxRolePermissionRelation::getPermissionId).collect(Collectors.toList());
        WxRole role = WxRole.builder()
                .id(id)
                .pids(permissionIds).build();
        if (rolePermissionRelationList.isEmpty()) {
            Result result = CommonResult.nullResult(role);
            return result;
        }
        Result result = CommonResult.successResult(role);
        return result;
//        return null;
    }

    @ApiOperation(("角色添加权限"))
    @PreAuthorize("hasAuthority('role-permission:create')")
    @PostMapping("/save")
    public Result save(@RequestBody WxRolePermissionRelation rolePermissionRelation) {
//        System.out.println("roles==="+userRoleRelation);
        if (rolePermissionRelation == null) {
            Result result = CommonResult.nullResult(null);
            return result;
        }
        rolePermissionRelationService.save(rolePermissionRelation);
        Result result = CommonResult.successResult(null);
        return result;
//        return null;
    }

}
